﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCore.Common.Redis;
using NetCore.IServices.User;
using NetCore.Model.Enity;
using System;
using System.Threading.Tasks;

namespace NetCore.WebApi.Controllers
{
    public class RedisController : BaseController
    {
        private readonly IMain_RedisCacheManager _redisCacheManager;
        private readonly IUserService _userService;

        public RedisController(IMain_RedisCacheManager redisCacheManager, IUserService userService)
        {
            _redisCacheManager = redisCacheManager;
            _userService = userService;
        }

        /// <summary>
        /// 测试Redis
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<IActionResult> Redis(int id)
        {
            var key = $"Redis{id}";
            SysUser user;
            if (_redisCacheManager.Get<object>(key) != null)
            {
                user = _redisCacheManager.Get<SysUser>(key);
            }
            else
            {
                user = await _userService.QueryByID(id);
                _redisCacheManager.Set(key, user, TimeSpan.FromHours(2));//缓存2小时
            }

            return Ok(user);
        }
    }
}